package demo2;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Object> {
    private String url;
    private String name;
    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }
    @Override
    public Object call() throws Exception {
        WebDownload webdownload = new WebDownload();
        webdownload.download(url,name);
        return true;
    }
    public static class WebDownload {
        void download(String url,String name){
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("http://img.hb.aicdn.com/e62c9422ad024a8a73fdfa5ddb6274a153a2b9e56b95e-w8j1J8_fw320", "1.jpg");
        TestCallable t2 = new TestCallable("https://i02piccdn.sogoucdn.com/f2e974d41cdbf4b6", "2.jpg");
        TestCallable t3 = new TestCallable("https://i01piccdn.sogoucdn.com/37a201bd3e24fb8e", "3.jpg");
        //创建服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        //提交线程,返回结果future
        Future<Object> future1 = service.submit(t1);
        Future<Object> future2 = service.submit(t2);
        Future<Object> future3 = service.submit(t3);
        //获取future
        Object res1 = future1.get();
        Object res2 = future2.get();
        Object res3 = future3.get();
        //关闭服务
        service.shutdown();
    }
}
